<?php
/**
 * Created by PhpStorm.
 * User: DD
 * Date: 2016/4/18
 * Time: 22:59
 */

namespace app\admin\services;

use app\common\services\BaseService;
use app\common\model\RoleMenu;

class RoleService extends BaseService
{
    public function getIdTitleArray()
    {
        return $this->getModelInstance()->field('id,title')->select();
    }

    public function savePower($roleId, $menuIds)
    {
        $roleMenuService = new RoleMenuService();
        $roleMenuService->savePower($roleId, $menuIds);
    }

    public function saveModel($data, $isAdding = null)
    {
        try {
            $this->getModelInstance()->startTrans();
            $role_id = parent::saveModel($data);
            if (!empty($data['id'])) { // for edit
                $role_id = intval($data['id']);
            } else {
                $role_id = $role_id[0];
            }
            if (isset($data['tokens'])) {
                $tokens = json_decode($data['tokens'], true);
                $roleMenu = RoleMenu::instance();
                if (!empty($tokens) && is_array($tokens)) {
                    if (!empty($data['id'])) { // for edit
                        $roleMenu->where(['role_id' => $role_id])->delete();
                    }
                    foreach ($tokens as $token) {
                        $roleMenu->add([
                            'menu_token' => $token['menu_token'],
                            'role_id' => $role_id,
                        ]);
                    }
                }
            }
            $this->getModelInstance()->commit();
            return [true]; // TODO: Change the autogenerated stub
        } catch (\Exception $ex) {
            $this->getModelInstance()->rollback();
            return [false, $ex->getMessage()];
        }
    }
}